#! /usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os
import time
import threading
import xml.etree.ElementTree as ET
import global_var
from plate_shape import SDFReader

log = global_var.gl_log

MAIN_COLL_NAME = "flattensys"
SHAPELINE_DATA = "shape_detail"
#file monitor: 监控shape数据的读写
class CPlateShapeSave(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        
    def run(self):
        while global_var.gl_RUNNING:
            sleep_time = 1.0
            for _it in global_var.gl_lst_shpsav:
                if _it["ctime"]:
                    tm_now = int(time.now())
                    if tm_now - _it["ctime"] > 86400:#if the time over one day, remove the data @2020-3-1
                        global_var.gl_lst_shpsav.remove(_it)
                        continue

                if len(_it["file_name"]):
                    try:
                        file_name = _it["file_name"]
                        oid = _it["oid"]
                        pid = _it["pid"]
                        sdf = SDFReader()#(file_name)

                        sdf.read_folder(file_name)
                        log.info("shape save: read shap: {}".format(file_name))
                        data_shp = sdf.read_shape(file_name)
                        
                        root = ET.fromstring(sdf.Folder)

                        shapedata = self.read_xml(root)

                        file_complete = True
                 
                        if self.db_proc and oid:
                            sav_values = {}
                            sav_values["recv_shape"] = 1
                            sav_values.update(shapedata)
                            
                            self.db_proc.update(MAIN_COLL_NAME, oid, sav_values)
                            self.db_proc.insert(SHAPELINE_DATA,{"_id":oid,"plate_id":pid,"data":data_shp,"filename":file_name})
                        
                        global_var.gl_lst_shpsav.remove(_it)
                    except Exception as e:
                        log.error("Plate file mon: {}".format(e))

            time.sleep(sleep_time)

def run_test():
    pass

if __name__=="__main__":
    run_test()